<?php

namespace app\lnk\controller\api;

use lite\lib\JwtAuth;
use lite\lib\help;
use app\lnk\model\DynamicModel;
use app\lnk\model\MessageModel;
use app\lnk\model\UserModel;
use app\lnk\model\UserFollowModel;
use app\lnk\model\UserBindModel;
use app\lnk\model\UserLikeDynamicModel;
use app\lnk\service\DynamicService;
use app\lnk\service\UserService;
use EasyWeChat\Factory;
use lite\service\ConfigService;
use think\facade\Db;
use think\Request;
use app\appcenter\lib\AppIHookService;

class User
{
    public function login_empower(Request $request)
    {
        $code = $request->post('code');
        $type = $request->post('type');
        if (!$code || !$type) return error('授权失败', 500001);
        if($type==1){
            $config = [
                'app_id' => ConfigService::get('lnk', 'lnk_app_id', ''),
                'secret' => ConfigService::get('lnk', 'lnk_app_secret', ''),
                'response_type' => 'array',
            ];
            $app = Factory::miniProgram($config); 
            $response = $app->auth->session($code);
            if (!$response['openid']) return error('授权失败', 500001);
            $info = UserBindModel::where('bind', $response['openid'])->where('type',$type)->find();
            if(!empty($info['user_id'])){
                if(!empty($response['unionid']) && empty($info['wx_unionid'])){
                    UserBindModel::where('id', $info['id'])->update(['wx_unionid'=>$response['unionid']]);
                }
                $info = UserModel::field(UserService::user_find())->find($info['user_id']);
                $info = UserService::user_other($info);
                $data['info'] = $info;
                $data['openid'] = $response['openid'];
                $data['token'] = JwtAuth::signToken($info['id']);
                return success('success', $data);
            }else{
                if($info){
                    if(!empty($response['unionid'])){
                        //非第一次进入的新用户未填个人信息的用户 查询 同unionid的帐户
                        $un_info = UserBindModel::where('wx_unionid', $response['unionid'])->where('user_id','>',0)->find();
                        if(!empty($un_info['user_id'])){
                            UserBindModel::where('id', $info['id'])->update(['user_id'=>$un_info['user_id'],'wx_unionid'=>$response['unionid']]);
                            $info = UserModel::field(UserService::user_find())->find($un_info['user_id']);
                            $info = UserService::user_other($info);
                            $data['info'] = $info;
                            $data['openid'] = $response['openid'];
                            $data['token'] = JwtAuth::signToken($info['id']);
                            return success('success', $data);
                        }
                    }
                    $l_id = $info['id'];
                    
                }else{
                    //第一次进入的新用户

                    $model = [
                        'bind' => $response['openid'],
                        'type' => 1,
                        'create_time' => time()
                    ];

                    if(!empty($response['unionid'])){
                        $model += ['wx_unionid'=>$response['unionid']];

                        $un_info = UserBindModel::where('wx_unionid', $response['unionid'])->where('user_id','>',0)->find();
                        if(!empty($un_info['user_id'])){
                            $model += ['user_id'=>$un_info['user_id']];
                            (new UserBindModel)->insert($model);
                            $info = UserModel::field(UserService::user_find())->find($un_info['user_id']);
                            $info = UserService::user_other($info);
                            $data['info'] = $info;
                            $data['openid'] = $response['openid'];
                            $data['token'] = JwtAuth::signToken($info['id']);
                            return success('success', $data);
                        }
                    }
                    $l_id = (new UserBindModel)->insertGetId($model);

                }
                $data = md5(gen_random_str(10).$l_id);
                cache($data,$l_id,60*60);
                return error('新用户', 500003,$data);
            }

            

        }
    }

    public function login_users_info(Request $request)
    {
        $key = $request->post('key');
        $nickname = $request->post('nickname');
        $active = $request->post('active');
        $code = $request->post('code');
        if(!$key || !$nickname || !$active || !$code){
            return error('登陆出错', 500006);
        }
        $l_id = cache($key);
        if($l_id){
            $un_info = UserBindModel::find($l_id);
            if($un_info && !$un_info['user_id']){


                $config = [
                    'app_id' => ConfigService::get('lnk', 'lnk_app_id', ''),
                    'secret' => ConfigService::get('lnk', 'lnk_app_secret', ''),
                    'response_type' => 'array',
                ];
                $app = Factory::miniProgram($config);
                $response = $app->phone_number->getUserPhoneNumber($code);
        
                if ($response['errmsg'] == 'ok') {
                    $model = [
                        'name' => $nickname,
                        'avatar' => $active,
                        'type' => 1,
                        'mobile' => $response['phone_info']['phoneNumber'],
                        'ip' => $request->ip(),
                        'create_time' => time()
                    ];
                    $res = help::ip($request->ip());
                    if ($res['status'] == 0) {
                        $model = help::ip_text($model, $res['result']);
                    }
                    cache($key,null);
                    AppIHookService::Hook_Run('add_user',$model,['request'=>$request,'bind'=>$un_info['bind']]);
                    $user_id = (new UserModel)->insertGetId($model);
                    AppIHookService::Hook_Run('add_user_out',$model,['uid'=>$user_id,'request'=>$request,'bind'=>$un_info['bind']]);
                    UserBindModel::where('id', $l_id)->update(['user_id'=>$user_id]);
                    $info = UserModel::field(UserService::user_find())->find($user_id);
                    $info = UserService::user_other($info);
                    $data['info'] = $info;
                    $data['openid'] = $un_info['bind'];
                    $data['token'] = JwtAuth::signToken($info['id']);
                    return success('success', $data);
                }
            }

        }
        return error('登陆出错', 500006);
    }

    public function wx_empower(Request $request)
    {

        $code = $request->post('code');
        if (!$code) return error('授权失败', 500001);

        $config = [
            'app_id' => ConfigService::get('lnk', 'lnk_app_id', ''),
            'secret' => ConfigService::get('lnk', 'lnk_app_secret', ''),
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $response = $app->auth->session($code);
        if (!$response['openid']) return error('授权失败', 500001);

        $info = UserModel::where('weixin_openid', $response['openid'])->field(UserService::user_find())->find();
        if (!$info) {
            $model = [
                'name' => '用户' . rand(100000, 999999),
                'avatar' => $request->domain() . '/static/images/avatar.png',
                'weixin_openid' => $response['openid'],
                'type' => 1,
                'ip' => $request->ip(),
                'create_time' => time()
            ];
            $res = help::ip($request->ip());
            if ($res['status'] == 0) {
                $model = help::ip_text($model, $res['result']);
            }
            (new UserModel)->insert($model);
            $info = UserModel::where('weixin_openid', $response['openid'])->field(UserService::user_find())->find();
        }
        $info = UserService::user_other($info);
        $data['info'] = $info;
        $data['token'] = JwtAuth::signToken($info['id']);
        return success('success', $data);
    }

    public function user_refresh_info(Request $request)
    {
        $uid = $request->uid;
        $info = UserModel::where('id', $uid)->field(UserService::user_find())->find();
        $info = UserService::user_other($info);
        $data['info'] = $info;
        $data['token'] = JwtAuth::signToken($info['id']);
        return success('success', $data);
    }

    public function edit_user_info(Request $request)
    {
        $uid = $request->uid;
        $model = [];
        $model['name'] = $request->post('name');
        $model['avatar'] = $request->post('avatar');
        $model['gender'] = $request->post('gender');
        $model['age'] = $request->post('age');
        $model['career'] = $request->post('career');
        $model['update_time'] = time();
        AppIHookService::Hook_Run('edit_user',$model,['request'=>$request]);
        UserModel::where('id', $uid)->update($model);
        AppIHookService::Hook_Run('edit_user_out',$model,['request'=>$request]);

        return success('修改成功 🎉');
    }

    public function user_bind_mobile(Request $request)
    {
        $uid = $request->uid;
        $code = $request->post('code');
        if (!$code) return error('授权失败', 500001);

        $config = [
            'app_id' => ConfigService::get('lnk', 'lnk_app_id', ''),
            'secret' => ConfigService::get('lnk', 'lnk_app_secret', ''),
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $response = $app->phone_number->getUserPhoneNumber($code);

        if ($response['errmsg'] == 'ok') {
            $model['mobile'] = $response['phone_info']['phoneNumber'];
            $model['update_time'] = time();
            UserModel::where('id', $uid)->update($model);

            $data = UserModel::where('id', $uid)->field(UserService::user_find())->find();
            $data = UserService::user_other($data);

            return success('操作成功 🎉', $data);
        } else {
            return error('授权失败', 500001);
        }
    }

    public function user_refresh_ip(Request $request)
    {
        $uid = $request->uid;
        $res = help::ip($request->ip());
        if ($res['status'] == 0) {
            $model = help::ip_text([], $res['result']);
            UserModel::where('id', $uid)->update($model);

            $data = UserModel::where('id', $uid)->field(UserService::user_find())->find();
            $data = UserService::user_other($data);

            return success('刷新成功 🎉', $data);
        } else {
            return error('刷新失败', 500001);
        }
    }

    public function user_details(Request $request)
    {
        $uid = $request->uid;
        $user_id = $request->get('user_id', 0);
        $data = UserModel::where('id', $user_id)->field(UserService::user_find())->find();
        if (!$data) return error('未找到用户或用户异常！', 500101);
        $data = UserService::user_other($data, $uid);
        UserModel::where('id', $user_id)->update([
            'weigh' => Db::raw('weigh+1')
        ]);
        return success('成功', $data);
    }

    public function user_publish_content(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type');
        $user_id = $request->get('user_id', 0);
        $status = [0, 1];
        if ($user_id > 0) {
            $uid = $user_id;
            $status = [1];
        }
        if ($type == 0) {
            $data = DynamicModel::where('user_id', $uid)
                ->whereIn('status', $status)
                ->order('id', 'desc')
                ->field(DynamicService::dynamic_find())
                ->paginate(6)->toArray();
            if ($data) $data = DynamicService::dynamic_map($data, $user_id > 0, $request->uid);
        } else {
            $ids = UserLikeDynamicModel::where('user_id', $uid)
                ->where('status', 1)
                ->order('id', 'desc')
                ->column('dynamic_id');
            $ids_ordered = implode(',', $ids);
            if (count($ids)) {
                $data = DynamicModel::where('status', 1)
                    ->whereIn('id', $ids)
                    ->orderRaw("FIELD(id, $ids_ordered)")
                    ->field(DynamicService::dynamic_find())
                    ->paginate(6)->toArray();
                if ($data) $data = DynamicService::dynamic_map($data, $user_id > 0, $request->uid);
            }
        }

        return success('成功', $data ?? '');
    }

    public function follow_user(Request $request)
    {
        $uid = $request->uid;
        $uname = $request->post('uname');
        $user_id = $request->post('user_id');
        $is_follow = $request->post('is_follow');
        if ($user_id == $uid) return error('您不能关注您自己', 500201);
        if ($is_follow) {
            UserFollowModel::where('user_id', $uid)
                ->where('follow_user_id', $user_id)
                ->delete();
        } else {
            UserFollowModel::insert([
                'user_id' => $uid,
                'follow_user_id' => $user_id,
                'create_time' => time()
            ]);
            $message = $uname . ' 关注了你。';
            $avatar_url = '/pages/user/details?id=' . $uid;
            (new MessageModel())->send($user_id, '收到关注', $message, $uid, '', $avatar_url);
            UserModel::where('id', $user_id)->update([
                'weigh' => Db::raw('weigh+10')
            ]);
        }
        return success('成功', '');
    }

    public function user_follow(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type');
        if ($type == 1) {
            $data = UserFollowModel::where('user_id', $uid)
                ->order('id', 'desc')
                ->field('id,follow_user_id')
                ->paginate(15)->toArray();
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['user'] = UserModel::where('id', $v['follow_user_id'])
                    ->field('id,name,avatar')
                    ->find();
                $data['data'][$k]['is_follow'] = UserFollowModel::where('user_id', $v['follow_user_id'])
                    ->where('follow_user_id', $uid)
                    ->count() ? true : false;
            }
        } else {
            $data = UserFollowModel::where('follow_user_id', $uid)
                ->order('id', 'desc')
                ->field('id,user_id')
                ->paginate(15)->toArray();
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['user'] = UserModel::where('id', $v['user_id'])
                    ->field('id,name,avatar')
                    ->find();
                $data['data'][$k]['is_follow'] = UserFollowModel::where('user_id', $uid)
                    ->where('follow_user_id', $v['user_id'])
                    ->count() ? true : false;
            }
        }

        return success('成功', $data);
    }

}
